from pygrabber.dshow_graph import FilterGraph
import cv2
import time


graph = FilterGraph()
devices = graph.get_input_devices()
target_camera = "USB Camera"  # 替换为你的摄像头名称

start = time.time()
if target_camera in devices:
    index = devices.index(target_camera)
    cap = cv2.VideoCapture(index, cv2.CAP_DSHOW)
    print(f"初始化耗时: {time.time() - start:.2f}s")
else:
    print("未找到指定摄像头！")
    exit()

if not cap.isOpened():
    print("无法打开摄像头")
    exit()


start = time.time()

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840) # 设置分辨率
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G')) # 跳过协议协商，加速

print(f"设置分辨率耗时: {time.time() - start:.2f}s")
print(f"当前分辨率: {cap.get(cv2.CAP_PROP_FRAME_WIDTH)}x{cap.get(cv2.CAP_PROP_FRAME_HEIGHT)}")


# 拍摄一帧
# cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G')) # 跳过协议协商，加速

for _ in range(3):  # 丢弃前3帧（预热）
    cap.read()

for i in range(20):
    start = time.time()
    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头！")
        exit()
    print(f"读取帧耗时: {time.time() - start:.2f}s")
    start = time.time()
    cv2.imwrite("data/frame" + str(i) + ".jpg", frame)  # 保存整张图像
    print(f"保存耗时: {time.time() - start:.2f}s")


# 拆分为左右眼图像（左眼=左侧1920x1080，右眼=右侧1920x1080）
# left_img = frame[:, :1920, :]  # 左眼（前1920列）
# right_img = frame[:, 1920:, :]  # 右眼（后1920列）

# # 保存图像
# cv2.imwrite("left_eye.jpg", left_img)
# cv2.imwrite("right_eye.jpg", right_img)
start = time.time()
cv2.imwrite("frame.jpg", frame)  # 保存整张图像
print(f"保存耗时: {time.time() - start:.2f}s")

fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
fourcc_str = "".join([chr((fourcc >> 8 * i) & 0xFF) for i in range(4)])
print(f"当前格式: {fourcc_str}")  # 常见如MJPG/YUY2/NV12

formats = {
    'MJPG': cv2.VideoWriter_fourcc('M','J','P','G'),
    'YUY2': cv2.VideoWriter_fourcc('Y','U','Y','2'),
    'NV12': cv2.VideoWriter_fourcc('N','V','1','2')
}

for name, codec in formats.items():
    cap.set(cv2.CAP_PROP_FOURCC, codec)
    ret, frame = cap.read()
    if ret and frame.mean() > 10:  # 非全黑
        print(f"有效格式: {name}")

fps = cap.get(cv2.CAP_PROP_FPS)  # 获取摄像头当前帧率
print(f"摄像头支持的最大帧率: {fps} FPS")

# 释放摄像头
cap.release()

